package com.csqiusheng.zyydt.http

import com.csqiusheng.base.utils.LogUtil
import com.jakewharton.retrofit2.adapter.kotlin.coroutines.CoroutineCallAdapterFactory
import okhttp3.Interceptor
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Converter
import retrofit2.Retrofit
import retrofit2.converter.moshi.MoshiConverterFactory
import java.util.concurrent.TimeUnit

object RetrofitUtil {
    private var retrofit: Retrofit? = null
    private var okHttpClient: OkHttpClient? = null
    private val logInterceptor = HttpLoggingInterceptor(object : HttpLoggingInterceptor.Logger {
        override fun log(message: String) {
            LogUtil.i("http", message)
        }

    }).also {
        it.level = HttpLoggingInterceptor.Level.BODY
    }
    private var converterFactory: Converter.Factory = MoshiConverterFactory.create()
    var baseUrl: String? = null

    private val interceptors: MutableList<Interceptor> = mutableListOf()
    fun addInterceptor(interceptor: Interceptor)  {
        interceptors += interceptor
    }
    private fun getOkHttpClient(): OkHttpClient? {
        if (okHttpClient == null) {
            okHttpClient = OkHttpClient.Builder().apply {
                this.readTimeout(60, TimeUnit.SECONDS)
                this.writeTimeout(60, TimeUnit.SECONDS)
                this.connectTimeout(60, TimeUnit.SECONDS)
                interceptors.forEach {
                   this.addInterceptor(it)
                }
                this.addNetworkInterceptor(logInterceptor)
            }.build()

        }
        return okHttpClient
    }

    fun getRetrofit(): Retrofit {
        if (retrofit == null) {
            val retrofitBuilder = Retrofit.Builder()
            baseUrl?.let {
                retrofitBuilder.baseUrl(it)
            }

            retrofitBuilder.addCallAdapterFactory(CoroutineCallAdapterFactory())
            retrofitBuilder.addConverterFactory(converterFactory)
            getOkHttpClient()?.let {
                retrofitBuilder.client(it)
            }
            retrofit = retrofitBuilder.build()
        }
        return retrofit!!
    }

}